<template>
    <div class="role-management">
        <div class="page-header">
            <h1>角色管理</h1>
            <a-button type="primary" @click="showAddModal = true">
                <template #icon>
                    <PlusOutlined />
                </template>
                添加角色
            </a-button>
        </div>

        <!-- 搜索和筛选 -->
        <div class="search-section">
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-input-search v-model:value="searchKeyword" placeholder="搜索角色名称或编码" @search="handleSearch" />
                </a-col>
                <a-col :span="4">
                    <a-button @click="resetFilters">重置筛选</a-button>
                </a-col>
            </a-row>
        </div>

        <!-- 角色列表 -->
        <div class="role-table">
            <a-table :columns="columns" :data-source="filteredRoles" :pagination="pagination" :loading="loading"
                row-key="id" @change="handleTableChange">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'status'">
                        <a-tag :color="record.deleted === 0 ? 'green' : 'red'">
                            {{ record.deleted === 0 ? '正常' : '禁用' }}
                        </a-tag>
                    </template>
                    <template v-else-if="column.key === 'action'">
                        <a-space>
                            <a-button type="link" @click="editRole(record)">编辑</a-button>
                            <a-button type="link" @click="viewRole(record)">查看</a-button>
                            <a-button type="link" @click="assignPermissions(record)">分配权限</a-button>
                            <a-popconfirm title="确定要删除这个角色吗？" @confirm="deleteRole(record.id)">
                                <a-button type="link" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </div>

        <!-- 添加/编辑角色弹窗 -->
        <a-modal v-model:open="showAddModal" :title="isEditing ? '编辑角色' : '添加角色'" width="500px" @ok="handleSubmit"
            @cancel="handleCancel">
            <a-form ref="formRef" :model="roleForm" :rules="formRules" layout="vertical">
                <a-form-item label="角色名称" name="name">
                    <a-input v-model:value="roleForm.name" placeholder="请输入角色名称" />
                </a-form-item>
                <a-form-item label="角色编码" name="code">
                    <a-input v-model:value="roleForm.code" placeholder="请输入角色编码" />
                </a-form-item>
                <a-form-item label="角色描述" name="description">
                    <a-textarea v-model:value="roleForm.description" :rows="3" placeholder="请输入角色描述" />
                </a-form-item>
            </a-form>
        </a-modal>

        <!-- 权限分配弹窗 -->
        <a-modal v-model:open="showPermissionModal" title="分配权限" width="600px" @ok="handlePermissionSubmit" @cancel="handlePermissionCancel">
            <a-form layout="vertical">
                <a-form-item label="角色">
                    <span>{{ currentRole?.name }}</span>
                </a-form-item>
                <a-form-item label="选择权限">
                    <a-tree
                        v-model:checkedKeys="selectedPermissions"
                        :tree-data="permissionTree"
                        checkable
                        :defaultExpandAll="true"
                        :field-names="{ children: 'children', title: 'name', key: 'id' }"
                    />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { 
    addRoleToPermissions,
    selectAllRoles,
    createRole,
    updateRole,
    deleteRole as deleteRoleApi
} from '@/api/user/sysRoleController'
import { 
    getAllMenu,
} from '@/api/user/sysPermissionController'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const showAddModal = ref(false)
const showPermissionModal = ref(false)
const isEditing = ref(false)
const roles = ref([])
const permissions = ref([])
const currentRole = ref()
const selectedPermissions = ref([])

// 角色表单
const roleForm = reactive({
    id: undefined,
    name: '',
    code: '',
    description: ''
})

// 表单验证规则
const formRules = {
    name: [{ required: true, message: '请输入角色名称' }],
    code: [{ required: true, message: '请输入角色编码' }]
}

// 分页配置
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
    {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
        width: 150
    },
    {
        title: '角色编码',
        dataIndex: 'code',
        key: 'code',
        width: 150
    },
    {
        title: '角色描述',
        dataIndex: 'description',
        key: 'description',
        width: 200
    },
    {
        title: '状态',
        dataIndex: 'deleted',
        key: 'status',
        width: 80
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 150
    },
    {
        title: '操作',
        key: 'action',
        width: 250,
        fixed: 'right'
    }
]

// 计算属性
const filteredRoles = computed(() => {
    return roles.value.filter((role) => {
        const keywordMatch = !searchKeyword.value ||
            role.name?.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
            role.code?.toLowerCase().includes(searchKeyword.value.toLowerCase())
        return keywordMatch
    })
})

const permissionTree = computed(() => {
    return buildPermissionTree(permissions.value)
})

// 方法
const loadRoles = async () => {
    loading.value = true
    try {
        const response = await selectAllRoles()
        if ( response.code === '00000') {
            roles.value = response.data || []
            pagination.total = roles.value.length
        } else {
            message.error('获取角色列表失败')
        }
    } catch (error) {
        console.error('获取角色列表失败:', error)
        message.error('获取角色列表失败')
    } finally {
        loading.value = false
    }
}

const loadPermissions = async () => {
    try {
        const response = await getAllMenu()
        if (response.data && response.code === '00000') {
            permissions.value = response.data || []
        }
    } catch (error) {
        console.error('获取权限列表失败:', error)
    }
}

const buildPermissionTree = (permissions) => {
    const permissionMap = {}
    const roots = []

    // 创建权限映射
    permissions.forEach(permission => {
        permissionMap[permission.id] = { ...permission, children: [] }
    })

    // 构建树形结构
    permissions.forEach(permission => {
        if (permission.parentId === 0 || !permissionMap[permission.parentId]) {
            roots.push(permissionMap[permission.id])
        } else {
            permissionMap[permission.parentId].children.push(permissionMap[permission.id])
        }
    })

    return roots
}

const handleSearch = () => {
    pagination.current = 1
}

const resetFilters = () => {
    searchKeyword.value = ''
    pagination.current = 1
}

const handleTableChange = (pag) => {
    pagination.current = pag.current
    pagination.pageSize = pag.pageSize
}

const editRole = (role) => {
    isEditing.value = true
    Object.assign(roleForm, role)
    showAddModal.value = true
}

const viewRole = (role) => {
    message.info(`查看角色: ${role.name}`)
}

const assignPermissions = async (role) => {
    currentRole.value = role
    // 这里需要获取角色已有的权限，暂时设为空数组
    selectedPermissions.value = []
    showPermissionModal.value = true
}

const deleteRole = async (roleId) => {
    try {
        const response = await deleteRoleApi({ id: roleId })
        if (response.data && response.code === '00000') {
            message.success('删除角色成功')
            await loadRoles()
        } else {
            message.error('删除角色失败')
        }
    } catch (error) {
        console.error('删除角色失败:', error)
        message.error('删除角色失败')
    }
}

const handleSubmit = async () => {
    try {
        if (isEditing.value) {
            // 编辑角色
            const response = await updateRole(roleForm)
            if (response.data && response.code === '00000') {
                message.success('更新角色成功')
                await loadRoles()
            } else {
                message.error('更新角色失败')
            }
        } else {
            // 添加角色
            const response = await createRole(roleForm)
            if (response.data && response.code === '00000') {
                message.success('添加角色成功')
                await loadRoles()
            } else {
                message.error('添加角色失败')
            }
        }

        showAddModal.value = false
        resetForm()
    } catch (error) {
        console.error('操作失败:', error)
    }
}

const handlePermissionSubmit = async () => {
    if (!currentRole.value) return
    
    try {
        const response = await addRoleToPermissions({
            roleId: currentRole.value.id,
            permissionIds: selectedPermissions.value
        })
        if (response.data && response.code === '00000') {
            message.success('权限分配成功')
            showPermissionModal.value = false
        } else {
            message.error('权限分配失败')
        }
    } catch (error) {
        console.error('权限分配失败:', error)
        message.error('权限分配失败')
    }
}

const handlePermissionCancel = () => {
    showPermissionModal.value = false
    currentRole.value = undefined
    selectedPermissions.value = []
}

const handleCancel = () => {
    showAddModal.value = false
    resetForm()
}

const resetForm = () => {
    Object.assign(roleForm, {
        id: undefined,
        name: '',
        code: '',
        description: ''
    })
    isEditing.value = false
}

// 生命周期
onMounted(async () => {
    await Promise.all([
        loadRoles(),
        loadPermissions()
    ])
})
</script>

<style scoped>
.role-management {
    padding: 0;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.page-header h1 {
    margin: 0;
    color: #333;
}

.search-section {
    background: #f5f5f5;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 16px;
}

.role-table {
    background: #fff;
    border-radius: 8px;
}
</style>
